package com.btks.jswater.response;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class ResponseAdvice {

    @RestControllerAdvice(basePackages = "com.btks.jswater.controller")
    @Slf4j
    static class ResultResponseAdvice implements ResponseBodyAdvice<Object> {

        /**
         * <p>Title: supports</p>
         * <p>Description:该组件是否支持给定的控制器方法返回类型和所选的HttpMessageConverter类型。</p>
         * @param returnType 返回值类型
         * @param converterType 转换器类型
         */

        @Override
        public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
            // 过滤返回值为'void'的接口
            return !returnType.getMethod().getReturnType().isAssignableFrom(Void.TYPE);
        }

        @ExceptionHandler(value = ExceptionMessage.class)
        @ResponseBody
        public Result bizExceptionHandler(HttpServletRequest req, ExceptionMessage e){
            return new Result(e.getCode(),e.getMessage());
        }


        @Override
        public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
            Result<Object> responseVo = new Result<>();
            responseVo.setCode(200);
            responseVo.setMsg("success");
            responseVo.setData(o);
            return responseVo;
        }


        @ExceptionHandler(Exception.class)
        @ResponseBody
        public Result<Object> exceptionHandler(Exception e) {
            log.error(e.getMessage(), e);
            Result<Object> responseVo = new Result<>();
            responseVo.setCode(500);
            responseVo.setMsg(e.getMessage());
            responseVo.setData(e.getMessage());
            return responseVo;
        }

    }
}